"""处理院系管理的views"""

# =========== 导入模块 ===========
from django.shortcuts import render, redirect,reverse
# 导入类
from basicweb.models import Faculty
# 导入jsonresponse
from django.http import JsonResponse
# 引入数据库操作模块
from utils import sqlhelper


def index(request):
    """基础数据的views函数【第一次加载】"""

    return render(request, 'basic/faculty.html')



def list_values(request):
    """获取院系数据"""
    # 获取传递过来的数据
    q_str = request.POST.get('inputStr', '')
    # 准备SQL语句
    sql = """
       Select T3.Id,T3.Name, Count(T3.id2) As 'Number' 
    From 
    (
        Select T1.Id, T1.Name, T2.Id As "id2"
        from Basic_Faculty As T1
        Left Join Basic_Major As T2 On T1.id = T2.faculty_id
		where T1.Name Like '%s' ) As T3
    Group By T3.Id,T3.Name
    """ % ('%' + q_str + '%')
    # 获取数据
    response = sqlhelper.get_db_data_dict(sql, ['id', 'name', 'number'])
    # 判断
    if response['status']:
        return JsonResponse({'status': True, 'data': response['data']})
    else:
        return JsonResponse({'status': False, 'error': response['error']})


def add_value(request):
    """添加院系数据"""
    # 接收传递的值
    rec_name = request.POST.get('name')
    # 定义一个返回值的数据结构
    res = {}
    # 开始添加
    try:
        # 写入
        Faculty.objects.create(name=rec_name)
        # 修改状态
        res['status'] = True
    except Exception as e:
        res['status'] = False
        res['error'] = "添加数据写入到数据库出现异常，具体原因：" + str(e)
    # 返回
    return JsonResponse(res)


def edit_value(request):
    """修改院系信息"""
    # 接收传递的值
    rec_id = request.POST.get('id')
    rec_name = request.POST.get('name')
    # 定义一个返回值的数据结构
    res = {}
    # 开始添加
    try:
        # 写入
        Faculty.objects.filter(id=rec_id).update(name=rec_name)
        # 修改状态
        res['status'] = True
    except Exception as e:
        res['status'] = False
        res['error'] = "修改数据写入到数据库出现异常，具体原因：" + str(e)
    # 返回
    return JsonResponse(res)


def del_value(request):
    """删除院系信息"""
    # 接收一个院系的编号
    rec_id = request.POST.get('id')
    # 定义返回的数据结构
    res = {}
    # 开始删除
    try:
        # 开始删除
        Faculty.objects.filter(id=rec_id).first().delete()
        # 添加状态
        res['status'] = True
    except Exception as e:
        res['status'] = False
        res['error'] = "删除数据提交到数据库出现异常，具体原因：" + str(e)

    return JsonResponse(res)

